<template>
  <div class="performance-container">
    <!-- 顶部区域 -->
    <div class="dashboard-header">
      <div class="header-title">
        <h2>性能测试任务</h2>
        <el-tag type="info" effect="plain" class="header-tag">任务列表</el-tag>
      </div>
      <div class="header-actions">
        <div class="search-wrapper">
          <el-input 
            v-model="filterText" 
            placeholder="搜索任务名称" 
            class="search-input"
            clearable>
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="searchClick" class="search-btn">搜索</el-button>
        </div>
        <el-button type="primary" @click="popup('add')" class="create-btn">
          <el-icon><Plus /></el-icon>新建任务
        </el-button>
      </div>
    </div>
    
    <!-- 数据卡片 -->
    <div class="task-stats">
      <div class="stat-card">
        <div class="stat-value">{{ taskList.length }}</div>
        <div class="stat-label">当前任务</div>
        <div class="stat-icon running-icon1">
          <el-icon><List /></el-icon>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ getRunningCount }}</div>
        <div class="stat-label">运行中</div>
        <div class="stat-icon running-icon">
          <el-icon><Loading /></el-icon>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ getCompletedCount }}</div>
        <div class="stat-label">已完成</div>
        <div class="stat-icon completed-icon">
          <el-icon><SuccessFilled /></el-icon>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ getErrorCount }}</div>
        <div class="stat-label">异常</div>
        <div class="stat-icon error-icon">
          <el-icon><WarningFilled /></el-icon>
        </div>
      </div>
    </div>

    <!-- 表格区域 - 使用滚动容器 -->
    <el-scrollbar class="table-scrollbar" height="calc(100vh - 280px)">
      <div class="task-table-card">
        <el-table
          v-loading="tableLoading"
          :data="taskList"
          style="width: 100%"
          row-key="id"
          :border="false"
          stripe
          :height="tableHeight"
          highlight-current-row
          :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }">
          
          <!-- 选择列 -->
          <el-table-column type="selection" width="55" align="center" />
          
          <!-- 任务信息 -->
          <el-table-column label="任务信息" min-width="300">
            <template #default="{ row }">
              <div class="task-info">
                <div class="task-avatar-container">
                  <el-avatar :size="40" class="task-avatar" :style="{backgroundColor: getRandomColor(row.taskName)}">
                    {{row.taskName.substr(0,1).toUpperCase()}}
                  </el-avatar>
                </div>
                <div class="task-detail">
                  <div class="task-name">
                    <router-link :to="`/maskMgrDetail/`" @click="clickTaskManage(row)" class="task-name-link">
                      {{ row.taskName }}
                    </router-link>
                  </div>
                  <div class="task-meta">
                    <el-tag :type="row.taskType === '10' ? 'primary' : 'success'" 
                      size="small" 
                      effect="plain" 
                      class="meta-tag">
                      {{ taskTypeMap[row.taskType.toString()] || row.taskType }}
                    </el-tag>
                    <div class="meta-info">创建于 {{ formatTimeAgo(row.create_time) }}</div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <!-- 状态列 -->
          <el-table-column label="运行状态" align="center" width="120">
            <template #default="{ row }">
              <div class="status-cell">
                <div :class="['status-indicator', getStatusClass(row.status)]"></div>
                <span class="status-text">{{ row.status_display || getStatusText(row.status) || '未设置' }}</span>
              </div>
            </template>
          </el-table-column>
          
          <!-- 运行模式 -->
          <el-table-column label="运行模式" align="center" width="120">
            <template #default="{ row }">
              <el-tag 
                effect="plain" 
                size="small" 
                class="mode-tag"
                :type="getRunPatternType(row.runPattern)">
                {{ row.taskType_display}}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 分布式模式 -->
          <el-table-column label="分布式模式" align="center" width="120">
            <template #default="{ row }">
              <el-tag 
                effect="plain" 
                size="small" 
                :type="getDistributedModeType(row.distributed_mode)">
                {{ getDistributedModeText(row.distributed_mode) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <!-- 创建/更新信息 -->
          <el-table-column label="任务创建者" align="center" width="160">
            <template #default="{ row }">
              <div class="user-info">
                <div class="user-avatar">
                  <el-avatar :size="28" :style="{backgroundColor: getRandomColor(row.creator)}">
                    {{ row.creator ? row.creator.substr(0,1).toUpperCase() : 'U' }}
                  </el-avatar>
                </div>
                <span class="user-name">{{ row.creator }}</span>
              </div>
            </template>
          </el-table-column>
          
          <!-- 更新者 -->
          <el-table-column label="最后更新" align="center" width="160">
            <template #default="{ row }">
              <div v-if="row.modifier && row.update_time" class="update-info">
                <div class="update-by">{{ row.modifier }}</div>
                <div class="update-time">{{ formatTimeAgo(row.update_time) }}</div>
              </div>
              <div v-else-if="row.create_time" class="update-info">
                <div class="update-by">{{ row.creator || '系统' }}</div>
                <div class="update-time">{{ formatTimeAgo(row.create_time) }}</div>
              </div>
              <el-tag v-else size="small" effect="plain" type="info">未更新</el-tag>
            </template>
          </el-table-column>
          
          <!-- 备注 -->
          <el-table-column label="备注" align="center" min-width="200">
            <template #default="{ row }">
              <el-tooltip
                v-if="row.desc"
                class="box-item"
                effect="dark"
                :content="row.desc"
                placement="top-start"
              >
                <div class="desc-text">{{ row.desc }}</div>
              </el-tooltip>
              <span v-else class="no-data">暂无备注</span>
            </template>
          </el-table-column>
          
          <!-- 操作列 -->
          <el-table-column label="操作" fixed="right" width="280" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button 
                  @click="runTask(row.id)" 
                  type="primary" 
                  plain 
                  size="small" 
                  class="action-btn run-btn">
                  <el-icon><Promotion /></el-icon> 运行
                </el-button>
                <el-button 
                  @click="clickTaskManage(row)" 
                  type="success" 
                  plain 
                  size="small" 
                  class="action-btn manage-btn">
                  <el-icon><Menu /></el-icon> 管理
                </el-button>
                <el-dropdown trigger="click" @command="handleCommand($event, row)" class="action-dropdown">
                  <el-button size="small" class="more-btn">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="copy">
                        <el-icon><CopyDocument /></el-icon> 复制任务
                      </el-dropdown-item>
                      <el-dropdown-item divided command="delete" class="danger-item">
                        <el-icon><Delete /></el-icon> 删除任务
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>

          <!-- 空状态处理 -->
          <template #empty>
            <div class="empty-data">
              <el-empty :image-size="120" description="暂无任务数据">
                <template #description>
                  <p>暂无任务数据</p>
                </template>
                <el-button type="primary" @click="popup('add')">新建任务</el-button>
              </el-empty>
            </div>
          </template>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pages.current"
            background
            layout="total, prev, pager, next, jumper"
            :page-size="100"
            :total="pages.count"
            @current-change="currentPages"
          />
        </div>
      </div>
    </el-scrollbar>
  </div>

  <!-- 新增任务弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    destroy-on-close
    :before-close="clearValidation"
    class="task-dialog">
    <div class="dialog-content">
      <el-form :model="form" :rules="rulesPerf" ref="perfRef" label-position="top">
        <div class="form-row">
          <el-form-item label="任务名称" prop="taskName" class="form-item-half">
            <el-input v-model="form.taskName" maxlength="50" placeholder="请输入任务名称" />
          </el-form-item>
          <el-form-item label="所属项目" prop="project" class="form-item-half">
            <el-input v-model="form.proName" disabled />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="任务类型" prop="taskType" class="form-item-half">
            <el-radio-group v-model="selectTaskType" class="task-type-radio">
              <el-radio label="10">
                <div class="radio-content">
                  <el-icon class="radio-icon"><Tickets /></el-icon>
                  <span>普通任务</span>
                </div>
              </el-radio>
              <el-radio label="20">
                <div class="radio-content">
                  <el-icon class="radio-icon"><Timer /></el-icon>
                  <span>定时任务</span>
                </div>
              </el-radio>
            </el-radio-group>
            <div v-if="form.taskType === '20'" class="tip-box warning">
              <el-icon><InfoFilled /></el-icon>
              <span>定时任务下只允许创建一个场景！</span>
            </div>
          </el-form-item>
          <el-form-item label="运行模式" prop="distributed_mode" class="form-item-half">
            <el-radio-group v-model="form.distributed_mode" class="run-mode-radio" @change="onDistributedModeChange">
              <el-radio label="single">
                <div class="radio-content">
                  <el-icon class="radio-icon"><Monitor /></el-icon>
                  <span>单机模式</span>
                </div>
              </el-radio>
              <el-radio label="distributed">
                <div class="radio-content">
                  <el-icon class="radio-icon"><Connection /></el-icon>
                  <span>分布式模式</span>
                </div>
              </el-radio>
            </el-radio-group>
            <div v-if="form.distributed_mode === 'single'" class="tip-box info">
              <el-icon><InfoFilled /></el-icon>
              <span>单机模式下无需选择服务器，系统将自动分配本机资源。</span>
            </div>
            <div v-if="form.distributed_mode === 'distributed'" class="tip-box info">
              <el-icon><InfoFilled /></el-icon>
              <span>分布式模式需要配置主服务器和工作服务器。</span>
            </div>
          </el-form-item>
        </div>
        <!-- 分布式配置 -->
        <div v-if="form.distributed_mode === 'distributed'" class="distributed-config">
          <div class="form-row">
            <el-form-item label="主服务机" prop="master_server" class="form-item-half">
              <el-select 
                v-model="form.master_server" 
                placeholder="请选择主服务器"
                style="width: 100%"
                @change="handleMasterServerChange">
                <el-option
                  v-for="server in availableServers"
                  :key="server.id"
                  :label="`${server.name} (${server.host_ip}:${server.host_port})`"
                  :value="server.id">
                  <div class="server-option">
                    <span class="server-name">{{ server.name }}</span>
                    <el-tag 
                      :type="server.status === 'active' ? 'success' : 'danger'" 
                      size="small">
                      {{ server.status === 'active' ? '可用' : '不可用' }}
                    </el-tag>
                  </div>
                  <div class="server-address">{{ server.host_ip }}:{{ server.host_port }}</div>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="GUI端口" prop="gui_port" class="form-item-half">
              <el-select 
                v-model="form.gui_port" 
                placeholder="请选择GUI端口"
                style="width: 100%"
                :loading="portCheckLoading">
                <el-option
                  v-for="port in guiPorts"
                  :key="port.port"
                  :label="`端口 ${port.port}`"
                  :value="port.port"
                  :disabled="port.occupied">
                  <div class="port-option">
                    <span class="port-number">{{ port.port }}</span>
                    <el-tag 
                      :type="port.occupied ? 'danger' : 'success'" 
                      size="small">
                      {{ port.occupied ? '已占用' : '可用' }}
                    </el-tag>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="form-row">
            <el-form-item label="工作机" prop="worker_servers" class="form-item-full">
              <el-select 
                v-model="form.worker_servers" 
                multiple
                placeholder="请选择工作服务器"
                style="width: 100%">
                <el-option
                  v-for="server in availableWorkerServers"
                  :key="server.id"
                  :label="`${server.name} (${server.host_ip}:${server.host_port})`"
                  :value="server.id">
                  <div class="server-option">
                    <span class="server-name">{{ server.name }}</span>
                    <el-tag 
                      :type="server.status === 'active' ? 'success' : 'danger'" 
                      size="small">
                      {{ server.status === 'active' ? '可用' : '不可用' }}
                    </el-tag>
                  </div>
                  <div class="server-address">{{ server.host_ip }}:{{ server.host_port }}</div>
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="form-row">
            <el-form-item label="工作进程数" prop="total_workers" class="form-item-half">
              <el-input-number 
                v-model="form.total_workers" 
                :min="1" 
                :max="maxWorkers"
                placeholder="总工作进程数"
                style="width: 100%" />
              <div class="worker-info">
                <span>建议进程数: {{ recommendedWorkers }}</span>
                <span>最大可用: {{ maxWorkers }}</span>
              </div>
            </el-form-item>
          </div>
        </div>

        <el-form-item label="任务描述" prop="desc">
          <el-input 
            type="textarea" 
            v-model="form.desc" 
            placeholder="请输入任务描述" 
            :rows="3" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="clearValidation" plain>取消</el-button>
        <el-button type="primary" @click="addTask">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 日志查看对话框 -->
  <!-- 已整体删除 -->
</template>

<script>
import {mapMutations, mapState} from "vuex";
import {ElNotification, ElMessage, ElMessageBox} from "element-plus";
import { 
  Plus, 
  Promotion, 
  CopyDocument, 
  Menu, 
  Delete, 
  InfoFilled, 
  Search, 
  List, 
  Loading, 
  SuccessFilled, 
  WarningFilled,
  More,
  User,
  Edit,
  Tickets,
  Timer,
  Monitor,
  Connection
} from '@element-plus/icons-vue';

export default {
  components: {
    Plus,
    Promotion,
    CopyDocument,
    Menu,
    Delete,
    InfoFilled,
    Search,
    List,
    Loading,
    SuccessFilled,
    WarningFilled,
    More,
    User,
    Edit,
    Tickets,
    Timer,
    Monitor,
    Connection
  },
  data() {
    return {
      // 状态码映射
      taskTypeMap: {'10': '普通任务', '20': '定时任务'},
      filterText: '',
      taskList: [],
      pages: {
        count: 0,
        current: 1
      },
      addDlg: false,
      form: {
        taskName: '',
        desc: '',
        project: '',
        taskType: '10',
        creator : '',
        modifier : '',
        distributed_mode: 'single',
        master_server: null,
        worker_servers: [],
        total_workers: 1,
        gui_port: 8089,
      },
      dialogVisible: false,
      dialogTitle: '',
      tableLoading: false,
      rulesPerf: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        distributed_mode: [
          { required: true, message: '请选择运行模式', trigger: 'change' }
        ],
        master_server: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.distributed_mode === 'distributed') {
                if (!value) {
                  if (this.form.worker_servers && this.form.worker_servers.length > 0) {
                    callback(new Error('请选择主服务器'));
                  }
                } else if (this.form.worker_servers && this.form.worker_servers.includes(value)) {
                  callback(new Error('主服务器和工作服务器不能选择同一个'));
                }
              }
              callback();
            }, 
            trigger: 'change' 
          }
        ],
        worker_servers: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.distributed_mode === 'distributed') {
                if (!value || value.length === 0) {
                  if (this.form.master_server) {
                    callback(new Error('请选择工作服务器'));
                  }
                } else if (this.form.master_server && value.includes(this.form.master_server)) {
                  callback(new Error('主服务器和工作服务器不能选择同一个'));
                }
              }
              callback();
            }, 
            trigger: 'change' 
          }
        ],
        gui_port: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.distributed_mode === 'distributed' && !value) {
                callback(new Error('分布式模式下必须选择GUI端口'));
              } else {
                callback();
              }
            }, 
            trigger: 'change' 
          }
        ],
        total_workers: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.distributed_mode === 'distributed') {
                const maxWorkers = this.maxWorkers;
                if (!value || value < 1) {
                  callback(new Error('工作进程数不能小于1'));
                } else if (value > maxWorkers) {
                  callback(new Error(`工作进程数不能超过${maxWorkers}`));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            }, 
            trigger: 'blur' 
          }
        ]
      },
      statusMap: {
        '0': { text: '执行完成', type: 'success', class: 'status-completed' },
        '1': { text: '执行中', type: 'warning', class: 'status-running' },
        '99': { text: '执行失败', type: 'danger', class: 'status-error' }
      },
      colorCache: {},
      tableHeight: 'calc(100vh - 330px)', // 初始高度，将在mounted中重新计算
      resizeObserver: null,
      
      // 新增字段
      availableServers: [],
      guiPorts: [
        { port: 8089, occupied: false },
        { port: 8090, occupied: false },
        { port: 8091, occupied: false },
        { port: 8092, occupied: false },
        { port: 8093, occupied: false },
        { port: 8094, occupied: false },
        { port: 8095, occupied: false },
        { port: 8096, occupied: false }
      ],
      portCheckTimer: null,
      // showLogsDialog: false, // 日志对话框状态保留
      // logsLoading: false, // 日志加载状态保留
      // currentLogs: null, // 当前日志数据保留
      // portCheckLoading: false // 端口检查加载状态保留
    }
  },
  mounted() {
    this.calculateTableHeight();
    this.loadServers();
    this.startPortCheck();
    
    // 监听窗口大小变化
    this.resizeObserver = new ResizeObserver(() => {
      this.calculateTableHeight();
    });
    
    // 监听容器大小变化
    const container = document.querySelector('.table-scrollbar');
    if (container) {
      this.resizeObserver.observe(container);
    }
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.calculateTableHeight);
  },
  beforeUnmount() {
    // 组件卸载时移除事件监听器和观察器
    window.removeEventListener('resize', this.calculateTableHeight);
    
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
    
    // 清理端口检查定时器
    if (this.portCheckTimer) {
      clearInterval(this.portCheckTimer);
    }
  },
  computed: {
    ...mapState({
      pro: state => state.pro,
      envId: state => state.envId
    }),
    username() {
      return window.sessionStorage.getItem('username');
    },
    selectTaskType: {
      get() {
        return this.form.taskType.toString();
      },
      set(value) {
        this.form.taskType = value;
      }
    },
    getRunningCount() {
      return this.taskList.filter(task => task.status === '1').length;
    },
    getCompletedCount() {
      return this.taskList.filter(task => task.status === '0').length;
    },
    getErrorCount() {
      return this.taskList.filter(task => task.status === '99').length;
    },
    // 无数据时固定表格最小高度
    minTableHeight() {
      return this.taskList.length > 0 ? undefined : '400px';
    },
    
    // 计算可用的工作服务器（排除已选为主服务器的）
    availableWorkerServers() {
      return this.availableServers.filter(server => 
        server.id !== this.form.master_server
      );
    },
    
    // 计算最大工作进程数
    maxWorkers() {
      if (!this.form.worker_servers || this.form.worker_servers.length === 0) {
        return 1;
      }
      
      const selectedServers = this.availableServers.filter(server => 
        this.form.worker_servers.includes(server.id)
      );
      
      return selectedServers.reduce((total, server) => {
        return total + (server.max_workers || 4);
      }, 0);
    },
    
    // 计算推荐工作进程数
    recommendedWorkers() {
      return Math.ceil(this.maxWorkers * 0.7); // 推荐使用70%的资源
    }
  },
  methods: {
    ...mapMutations(['checkedTask']),

    // 计算表格高度
    calculateTableHeight() {
      // 根据实际DOM高度计算
      this.$nextTick(() => {
        const headerHeight = document.querySelector('.dashboard-header')?.offsetHeight || 0;
        const statsHeight = document.querySelector('.task-stats')?.offsetHeight || 0;
        const paginationHeight = document.querySelector('.pagination-container')?.offsetHeight || 0;
        
        // 计算表格可用高度（减去其他元素高度和间距）
        const availableHeight = window.innerHeight - headerHeight - statsHeight - paginationHeight - 120; // 120为各种padding和margin
        
        // 确保最小高度
        this.tableHeight = Math.max(availableHeight, 300) + 'px';
      });
    },

    async allTask(page, query) {
      this.tableLoading = true;
      try {
        const response = await this.$api.getPerformanceTask(this.pro.id, page, query)
        if (response.status === 200) {
          this.taskList = response.data.result;
          this.pages.count = response.data.count;
          this.pages.current = response.data.current;
          
          // 数据加载完成后重新计算表格高度
          this.$nextTick(() => {
            this.calculateTableHeight();
          });
        }
      } catch (error) {
        ElMessage({
          type: 'error',
          message: '获取任务列表失败',
          duration: 3000
        });
      } finally {
        this.tableLoading = false;
      }
    },

    currentPages(currentPage) {
      this.allTask(currentPage, this.filterText);
    },

    searchClick() {
      this.allTask(1, this.filterText)
    },

    clickTaskManage(data) {
      this.$router.push({ name: 'maskMgrDetail' });
      this.checkedTask(data)
    },

    async viewLogs(task) {
      // 已删除日志查看方法
    },

    async refreshLogs() {
      // 已删除刷新日志方法
    },

    popup(type) {
      this.dialogVisible = true;
      // 根据不同的对话框类型设置标题
      switch (type) {
        case 'add':
          this.dialogTitle = '创建新任务';
          this.form.creator = this.username;
          this.form.project = this.pro.id;
          this.form.proName = this.pro.name;
          // 加载服务器列表
          this.loadServers();
          delete this.form.modifier;
          break;

        default:
          this.dialogTitle = '';
          break;
      }
    },

    // 新增方法
    async loadServers() {
      try {
        const response = await this.$api.getServers(this.pro.id, 1);
        if (response.status === 200) {
          this.availableServers = response.data.result || [];
        }
      } catch (error) {
        console.error('加载服务器列表失败:', error);
        this.$message.error('加载服务器列表失败');
      }
    },

    async checkPortStatus() {
      if (!this.form.master_server) {
        return;
      }
      
      try {
        this.portCheckLoading = true;
        const response = await this.$api.checkServerPorts(this.form.master_server);
        if (response.status === 200) {
          const occupiedPorts = response.data.occupied_ports || [];
          this.guiPorts.forEach(port => {
            port.occupied = occupiedPorts.includes(port.port);
          });
          
          // 自动选择第一个可用端口
          const availablePort = this.guiPorts.find(port => !port.occupied);
          if (availablePort && !this.form.gui_port) {
            this.form.gui_port = availablePort.port;
          }
          
          // 如果当前选择的端口被占用，自动切换到可用端口
          if (this.form.gui_port && occupiedPorts.includes(this.form.gui_port)) {
            const fallbackPort = this.guiPorts.find(port => !port.occupied);
            if (fallbackPort) {
              this.form.gui_port = fallbackPort.port;
              this.$message({
                type: 'warning',
                message: `端口 ${this.form.gui_port} 被占用，已自动切换到端口 ${fallbackPort.port}`,
                duration: 3000
              });
            } else {
              this.$message({
                type: 'error',
                message: '所有端口都被占用，请稍后重试或联系管理员',
                duration: 3000
              });
            }
          }
        }
      } catch (error) {
        console.error('检查端口状态失败:', error);
        this.$message.error('检查端口状态失败，将使用默认端口');
      } finally {
        this.portCheckLoading = false;
      }
    },

    startPortCheck() {
      // 每30秒检查一次端口状态
      this.portCheckTimer = setInterval(() => {
        if (this.form.distributed_mode === 'distributed' && this.form.master_server) {
          this.checkPortStatus();
        }
      }, 30000);
    },

    handleMasterServerChange() {
      // 主服务器变化时重新检查端口状态
      this.form.gui_port = 8089; // 重置为默认端口
      this.checkPortStatus();
      
      // 清空已选择的工作服务器中包含主服务器的选项
      if (this.form.worker_servers.includes(this.form.master_server)) {
        this.form.worker_servers = this.form.worker_servers.filter(
          id => id !== this.form.master_server
        );
      }
    },

    clearValidation() {
      this.dialogVisible = false;
      if (this.$refs.perfRef) {
        this.$refs.perfRef.clearValidate(); // 添加条件检查
      }
      this.form = {
        taskName: '',
        desc: '',
        project: '',
        taskType: '10',
        creator : '',
        modifier : '',
        distributed_mode: 'single',
        master_server: null,
        worker_servers: [],
        total_workers: 1,
        gui_port: 8089,
      }
    },

    onDistributedModeChange() {
      if (this.form.distributed_mode === 'single') {
        this.form.master_server = null;
        this.form.worker_servers = [];
        this.form.gui_port = 8089;
        this.form.total_workers = 1;
      } else if (this.form.distributed_mode === 'distributed') {
        this.form.master_server = null;
        this.form.worker_servers = [];
        this.form.gui_port = 8089;
        this.form.total_workers = 1;
      }
    },

    async addTask() {
      this.$refs.perfRef.validate(async vaild => {
        if (!vaild) return;
        const params = { ...this.form };
        // 不再传递server_config_mode
        try {
          const response = await this.$api.createPerformanceTask(params);
          if (response.status === 201) {
            // 先重置表单数据
            this.form = {
              taskName: '',
              desc: '',
              project: '',
              taskType: '10',
              creator : '',
              modifier : '',
              distributed_mode: 'single',
              master_server: null,
              worker_servers: [],
              total_workers: 1,
              gui_port: 8089,
            };
            
            // 再关闭弹窗
            this.dialogVisible = false;
            
            // 最后显示成功消息并刷新列表
            ElMessage({
              type: 'success',
              message: '任务创建成功',
              duration: 1000
            });
            this.allTask(1);
          }
        } catch (error) {
          ElMessage({
            type: 'error',
            message: '添加失败: ' + (error.message || '未知错误'),
            duration: 3000
          });
        }
      })
    },

    delTask(id) {
      ElMessageBox.confirm('此操作将永久删除该任务, 是否继续?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(async () => {
          try {
            const response = await this.$api.delPerformanceTask(id)
            if(response.status === 204) {
              ElMessage({
                type: 'success',
                message: '删除成功!'
              });
              // 刷新页面
              this.allTask(this.pages.current);
            }
          } catch (error) {
            ElMessage({
              type: 'error',
              message: '删除失败: ' + (error.message || '未知错误'),
              duration: 3000
            });
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    async clickCopy(data) {
      const params = {...data};
      params.taskName = params.taskName + '_副本';
      try {
        const response = await this.$api.createPerformanceTask(params);
        if (response.status === 201) {
          ElMessage({
            type: 'success',
            message: '复制成功',
            duration: 1000
          });
          this.allTask(this.pages.current);
        }
      } catch (error) {
        ElMessage({
          type: 'error',
          message: '复制失败: ' + (error.message || '未知错误'),
          duration: 3000
        });
      }
    },

    async runTask(id) {
      if (!this.envId) {
        this.$message({
          type: 'warning',
          message: '当前未选中执行环境!',
          duration: 1000
        });
        return
      }
      const params = { taskId: id, env: this.envId };
      try {
        // 注意：这里不再调用updateTaskStatus方法，后端需要在运行任务时更新状态为"执行中"
        const response = await this.$api.runTask(id, params);
        if (response.status === 200) {
          ElNotification({
            title: '任务已启动',
            message: '请前往报告列表查看结果',
            type: 'success',
            duration: 3000,
            showClose: true,
            position: 'top-right',
          });
          
          // 刷新任务列表以获取最新状态
          this.refreshTaskList();
        }
      } catch (error) {
        // 注意：后端需要在任务启动失败时更新状态为"执行失败"
        ElMessage({
          type: 'error',
          message: '任务启动失败: ' + (error.message || '未知错误'),
          duration: 3000
        });
        
        // 刷新任务列表以获取最新状态
        this.refreshTaskList();
      }
    },
    
    // 刷新任务列表
    refreshTaskList() {
      // 延迟一小段时间后刷新列表，确保后端状态已更新
      setTimeout(() => {
        this.allTask(this.pages.current);
      }, 1000);
    },

    getStatusText(status) {
      return this.statusMap[status]?.text || status;
    },

    getStatusClass(status) {
      return this.statusMap[status]?.class || 'status-unknown';
    },


    getRunPatternType(runPattern) {
      const typeMap = {
        'loadtest': 'primary',
        'stresstest': 'warning',
        'spiketest': 'danger',
        'volumetest': 'success',
        'endurancetest': 'info',
        'baselinetest': ''
      };
      return typeMap[runPattern] || 'info';
    },

    // 分布式模式相关方法
    getDistributedModeText(mode) {
      const modeMap = {
        'single': '单机模式',
        'distributed': '分布式模式'
      };
      return modeMap[mode] || mode || '未设置';
    },

    getDistributedModeType(mode) {
      const typeMap = {
        'single': 'info',
        'distributed': 'warning'
      };
      return typeMap[mode] || 'info';
    },

    formatTimeAgo(timestamp) {
      if (!timestamp) return '';
      
      const date = new Date(timestamp);
      const now = new Date();
      const seconds = Math.floor((now - date) / 1000);
      
      if (seconds < 60) return '刚刚';
      
      const minutes = Math.floor(seconds / 60);
      if (minutes < 60) return `${minutes}分钟前`;
      
      const hours = Math.floor(minutes / 60);
      if (hours < 24) return `${hours}小时前`;
      
      const days = Math.floor(hours / 24);
      if (days < 7) return `${days}天前`;
      
      return this.$tools.rTime(timestamp).split(' ')[0];
    },

    getRandomColor(str) {
      if (!str) return '#909399';
      
      if (this.colorCache[str]) {
        return this.colorCache[str];
      }
      
      // 生成一个基于字符串的伪随机颜色
      let hash = 0;
      for (let i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
      }
      
      const colors = [
        '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
        '#3963BC', '#4EC9B0', '#FF9F43', '#9C27B0', '#00BCD4',
        '#795548', '#607D8B', '#FF5722', '#9E9E9E', '#4CAF50'
      ];
      
      const index = Math.abs(hash) % colors.length;
      this.colorCache[str] = colors[index];
      return this.colorCache[str];
    },
    
    handleCommand(command, row) {
      switch (command) {
        case 'copy':
          this.clickCopy(row);
          break;
        case 'delete':
          this.delTask(row.id);
          break;
      }
    }
  },
  created() {
    this.allTask(1)
  }
}
</script>

<style scoped>
/* 主容器样式 */
.performance-container {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background-color: #f5f7fa;
  overflow: hidden;
}

/* 头部区域样式 */
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.header-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-tag {
  font-weight: normal;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-input {
  width: 280px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.search-icon {
  color: #909399;
}

.search-btn {
  height: 32px;
  border-radius: 6px;
}

.create-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  border-radius: 6px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s;
}

.create-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 统计卡片样式 */
.task-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  flex-shrink: 0;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  position: relative;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  transition: all 0.3s;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.stat-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.stat-card:nth-child(1) {
  border-top: 3px solid #409EFF;
}
.stat-card:nth-child(2) {
  border-top: 3px solid #E6A23C;
}
.stat-card:nth-child(3) {
  border-top: 3px solid #67C23A;
}
.stat-card:nth-child(4) {
  border-top: 3px solid #F56C6C;
}

.running-icon {
  background-color: #E6A23C;
}
.running-icon1 {
  background-color: #409EFF;
}
.completed-icon {
  background-color: #67C23A;
}

.error-icon {
  background-color: #F56C6C;
}

/* 滚动容器样式 */
.table-scrollbar {
  flex: 1;
  overflow: hidden;
}

.table-scrollbar :deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

/* 表格卡片样式 */
.task-table-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 表格内容样式 */
:deep(.el-table) {
  --el-table-header-bg-color: #f5f7fa;
  --el-table-row-hover-bg-color: #f0f5ff;
  border-radius: 6px;
  overflow: hidden;
  flex: 1;
}

:deep(.el-table__header) {
  font-weight: 600;
}

:deep(.el-table__row) {
  transition: all 0.2s;
}

:deep(.el-table__row:hover) {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

/* 空状态样式 */
.empty-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
}

.empty-data p {
  margin-top: 0;
  margin-bottom: 20px;
  color: #909399;
}

/* 任务信息样式 */
.task-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-avatar-container {
  flex-shrink: 0;
}

.task-avatar {
  font-weight: 500;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.task-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.task-name {
  font-weight: 500;
  font-size: 14px;
  line-height: 1.5;
}

.task-name-link {
  color: #303133;
  text-decoration: none;
  transition: all 0.3s;
  position: relative;
}

.task-name-link:hover {
  color: var(--el-color-primary);
}

.task-name-link:hover::after {
  content: '';
  position: absolute;
  width: 100%;
  height: 2px;
  background-color: var(--el-color-primary);
  bottom: -2px;
  left: 0;
  border-radius: 1px;
}

.task-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.meta-tag {
  padding: 0 6px;
  height: 22px;
  line-height: 20px;
  font-size: 12px;
  border-radius: 4px;
}

.meta-info {
  color: #909399;
  font-size: 12px;
}

/* 状态样式 */
.status-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-running {
  background-color: #E6A23C;
  box-shadow: 0 0 0 2px rgba(230, 162, 60, 0.2);
}

.status-completed {
  background-color: #67C23A;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
}

.status-error {
  background-color: #F56C6C;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
}

.status-text {
  font-size: 13px;
}

/* 模式标签 */
.mode-tag {
  min-width: 60px;
}

/* 用户信息 */
.user-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.user-avatar {
  flex-shrink: 0;
}

.user-name {
  font-size: 13px;
  font-weight: 500;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 更新信息 */
.update-info {
  text-align: center;
}

.update-by {
  font-size: 13px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 2px;
}

.update-time {
  font-size: 12px;
  color: #909399;
}

/* 备注样式 */
.desc-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 13px;
  color: #606266;
}

.no-data {
  color: #c0c4cc;
  font-size: 13px;
}

/* 操作区域 */
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  height: 32px;
  border-radius: 4px;
  transition: all 0.3s;
}

.action-btn:hover {
  transform: translateY(-2px);
}

.more-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  border-radius: 4px;
}

:deep(.danger-item) {
  color: #F56C6C;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

/* 对话框样式 */
:deep(.task-dialog .el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  max-width: 90%;
}

:deep(.task-dialog .el-dialog__header) {
  padding: 20px;
  margin-right: 0;
  background: linear-gradient(135deg, #409EFF, #2a62ff);
}

:deep(.task-dialog .el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

:deep(.task-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

.dialog-content {
  padding: 20px;
}

/* 表单布局样式 */
.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 10px;
}

.form-item-half {
  flex: 1;
  min-width: 0;
}

.form-item-full {
  width: 100%;
}

:deep(.task-dialog .el-form-item__label) {
  padding-bottom: 8px;
  font-weight: 500;
}

:deep(.task-dialog .el-input__wrapper),
:deep(.task-dialog .el-textarea__inner) {
  border-radius: 6px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s;
}

:deep(.task-dialog .el-input__wrapper:hover),
:deep(.task-dialog .el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

:deep(.task-dialog .el-form-item:last-child) {
  margin-bottom: 0;
}

/* 任务类型和运行模式选择样式 */
.task-type-radio,
.run-mode-radio {
  width: 100%;
  display: flex;
  gap: 10px;
}

.task-type-radio .el-radio,
.run-mode-radio .el-radio {
  margin-right: 0;
  margin-bottom: 10px;
  padding: 10px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s ease;
  width: calc(50% - 5px);
}

.task-type-radio .el-radio:last-child,
.run-mode-radio .el-radio:last-child {
  margin-bottom: 0;
}

.task-type-radio .el-radio:hover,
.run-mode-radio .el-radio:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.task-type-radio .el-radio.is-checked,
.run-mode-radio .el-radio.is-checked {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.radio-content {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.radio-icon {
  font-size: 18px;
  color: #409eff;
}

/* 分布式配置区域样式 */
.distributed-config {
  margin-top: 10px;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

/* 服务器和端口选项样式 */
.server-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 0 5px;
}

.server-name {
  font-weight: 600;
  color: #303133;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.server-address {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 5px;
}

/* 端口选项样式 */
.port-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.port-number {
  font-weight: 600;
  color: #303133;
}

/* 工作进程数信息 */
.worker-info {
  margin-top: 8px;
  display: flex;
  gap: 20px;
  font-size: 12px;
  color: #909399;
}

/* 提示框样式 */
.tip-box {
  margin-top: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
}

.tip-box.warning {
  background-color: #fdf6ec;
  border: 1px solid #f5dab1;
  color: #e6a23c;
}

.tip-box.info {
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  color: #409eff;
}

/* 下拉选项样式 */
:deep(.el-select-dropdown__item) {
  padding: 8px 10px;
  height: auto;
}

:deep(.el-select-dropdown__item .server-option) {
  padding: 0;
}

:deep(.el-tag) {
  margin: 0;
}

/* 日志对话框样式 */
.logs-dialog {
  .el-dialog__body {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
  }
}

.logs-content {
  min-height: 200px;
}

.logs-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.log-section {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

.log-title {
  margin: 0;
  padding: 12px 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.log-title.error-title {
  background: #fef0f0;
  color: #f56c6c;
  border-bottom-color: #fbc4c4;
}

.log-content {
  padding: 16px;
  background: #fafafa;
  max-height: 300px;
  overflow-y: auto;
}

.log-content pre {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #606266;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.worker-log {
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.worker-title {
  margin: 0;
  padding: 8px 12px;
  background: #f0f9ff;
  border-bottom: 1px solid #e4e7ed;
  font-size: 13px;
  font-weight: 500;
  color: #409eff;
}

.error-content {
  background: #fef0f0;
}

.error-content pre {
  color: #f56c6c;
}

.no-logs {
  text-align: center;
  padding: 40px 20px;
}

/* 日志按钮样式 */
.logs-btn {
  margin-left: 8px;
}

.logs-btn:hover {
  background: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}
</style>